import nmap
import telnetlib
import re
import paramiko
import io

def scan_active_hosts(subnet):
    """扫描指定网段所有存活的主机"""
    # 实例化对象, portScanner()类用于实现对指定主机进行端口扫描
    nm = nmap.PortScanner()
    # 以指定方式扫描指定主机或网段的指定端口
    result = nm.scan(hosts=subnet, arguments='-n -sP')
    # 返回nmap扫描的主机清单，格式为列表类型
    return nm.all_hosts()


def is_ssh_open(ip):
    """判断ssh的22端口是否打开"""
    try:
        # 实例化对象
        tn = telnetlib.Telnet(host=ip, port=22, timeout=5)
        # read_until读取直到遇到了换行符或超时秒数。默认返回bytes类型，通过decode方法解码为字符 串。
        tn_result = tn.read_until(b"\n", timeout=5).decode('utf-8').lower()
    except Exception as e:
        tn_result = ''
    return True if re.findall('ssh', tn_result) else False

def login_ssh(host, user, passwd=None, pkey=None, cmd='hostname'):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if pkey:
        private = paramiko.RSAKey.from_private_key_file(pkey)
        client.connect(host, 22, user, pkey=private)
    if passwd:
        client.connect(host, 22, user, passwd)
    stdin, stdout, stderr = client.exec_command(cmd)
    return stdout.read().decode('utf-8')

if __name__ == '__main__':
    # hosts = scan_active_hosts('192.168.43.100/24')
    # print(hosts)
    # for host in hosts:
    #     if is_ssh_open(host):
    #         print(f'{host}的22端口打开')
    pkey = '/root/cmdb/scanhost/id_rsa'
    res = login_ssh('192.168.43.100', 'root', pkey=pkey, cmd='ip addr show ens33')
    print(res)
